package com.newflypig.jblog.controller;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.newflypig.jblog.exception.JblogException;
import com.newflypig.jblog.model.Article;
import com.newflypig.jblog.model.BlogCommon;
import com.newflypig.jblog.model.BlogConfig;
import com.newflypig.jblog.model.Pager;
import com.newflypig.jblog.model.Result;
import com.newflypig.jblog.service.IArticleService;
import com.newflypig.jblog.service.ITagService;
import com.newflypig.jblog.util.BlogUtils;

@Controller
@RequestMapping("/article")
public class ArticleController {
	
	@Autowired
	private IArticleService articleService;
	
	@Autowired
	private ITagService tagService;
	
	@Autowired
	private BlogCommon blogCommon;
	
	/**
	 * 删除文章，需要登录
	 * @param articleId
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/admin/{articleId}/delete", method=RequestMethod.POST)
	public ModelAndView delete(@PathVariable Integer articleId){		
		this.articleService.deleteById(articleId);
		Pager<Article> pagerArticles = this.articleService.findPagerForAdmin(1);
		ModelAndView mav = new ModelAndView("/article/list", "pagerArticles", pagerArticles);
		mav.addObject("urlName", "/article/admin/list");
		mav.addObject("pageTitle", "文章列表");
		mav.addObject("duoshuoId", BlogConfig.DUOSHUO_ID);
		return mav;
	}
	
	@RequestMapping(value = "/admin/{articleId}/delete-forever", method = RequestMethod.POST)
	public ModelAndView deleteForever(@PathVariable Integer articleId){
		this.articleService.deleteForeverById(articleId);
		Pager<Article> pagerArticles = this.articleService.findPagerForAdmin(1);
		ModelAndView mav = new ModelAndView("/article/list", "pagerArticles", pagerArticles);
		mav.addObject("urlName", "/article/admin/list");
		mav.addObject("pageTitle", "文章列表");
		mav.addObject("duoshuoId", BlogConfig.DUOSHUO_ID);
		return mav;
	}
	
	/**
	 * 添加文章GET请求，需要登录 
	 * @param session
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/admin/add",method=RequestMethod.GET)
	public ModelAndView add(HttpSession session){
		return new ModelAndView("article/add","pageTitle","添加文章");
	}
	
	/**
	 * 添加文章POST请求，需要登录
	 * @param article
	 * @param ctgrs
	 * @return
	 */
	@RequestMapping(value="/admin/add",method=RequestMethod.POST)
	public ModelAndView add(@ModelAttribute("article") Article article){
		Result result = new Result();
		System.out.println(article.getMenusStr());
		//对markdown中的<textarea>做一个转义
		article.setMarkdown(BlogUtils.textarea(article.getMarkdown()));
		
		try{
			this.articleService.add(article);
		}catch(DataIntegrityViolationException e){
			result.setCode(Result.FAIL);
			result.setMessage("重复的url设置，请编写一个唯一的url，然后重试。");
			return new ModelAndView("ajaxResult", "result", result);
		}
		
		//添加文章后，可以立即返回视图给用户，此时分配一个线程去更新内存中tags数据
		new Thread(() -> {
			blogCommon.setTags(this.tagService.findAll());
		}).start();
		
		return new ModelAndView("ajaxResult", "result", result);
	}
	
	/**
	 * 管理员端的文章列表请求
	 * @param page
	 * @return
	 */
	@RequestMapping(value = "/admin/list/page/{page}", method=RequestMethod.GET)
	public ModelAndView list(@PathVariable Integer page){
		Pager<Article> pagerArticles = this.articleService.findPagerForAdmin(page);
		ModelAndView mav = new ModelAndView("/article/list", "pagerArticles", pagerArticles);
		mav.addObject("urlName", "/article/admin/list");
		mav.addObject("pageTitle", "文章列表");
		mav.addObject("duoshuoId", BlogConfig.DUOSHUO_ID);
		return mav;
	}
	
	@RequestMapping(value = "/admin/trashbox/page/{page}", method = RequestMethod.GET)
	public ModelAndView trashBox(@PathVariable Integer page){
		Pager<Article> pagerArticles = this.articleService.findPagerForAdminTrashBox(page);
		ModelAndView mav = new ModelAndView("/article/list");
		mav.addObject("pagerArticles", pagerArticles);
		mav.addObject("trashbox", new Boolean(true));
		mav.addObject("urlName", "/article/admin/trashbox");
		mav.addObject("pageTitle", "垃圾箱");
		mav.addObject("duoshuoId", BlogConfig.DUOSHUO_ID);
		return mav;
	}
	
	/**
	 * 显示单篇文章
	 * @param articleUNorId article's urlName or articleId
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/show/{articleUNorId}",method=RequestMethod.GET)
	public ModelAndView show(@PathVariable String articleUNorId){
		ModelAndView mav = new ModelAndView("article/show");
		
		Article article=this.articleService.findByUNorId(articleUNorId);
		
		if(article != null){
			article.buildTagsStr();
			this.articleService.ratePP(article.getArticleId());
		}
		
		mav.addObject("article", article);
		mav.addObject("duoshuoId", BlogConfig.DUOSHUO_ID);
		return mav;
	}
	
	/**
	 * 更新文章GET请求，需要登录
	 * @param articleId
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/admin/{articleId}/update",method=RequestMethod.GET)
	public ModelAndView update(@PathVariable Integer articleId){
		
		Article article=this.articleService.findById(articleId);
		//对markdown中的<textarea>做一个转义
		article.setMarkdown(BlogUtils.textarea(article.getMarkdown()));
		
		article.buildTagsStr();
		article.buildMenusStr();
		
		ModelAndView mav = new ModelAndView("article/update");

		mav.addObject("article", article);
		return mav;
	}
	
	/**
	 * 更新文章POST请求，需要登录
	 * @param article
	 * @param ctgrs
	 * @return
	 * @throws JblogException 
	 */
	@RequestMapping(value="/admin/update",method=RequestMethod.POST)
	public ModelAndView update(@ModelAttribute("article") Article article) throws JblogException{		
		Result result = new Result();
		System.out.println(article.getMenusStr());
		try{
			this.articleService.update(article);
		}catch(DataIntegrityViolationException e){
			result.setCode(Result.FAIL);
			result.setMessage("重复的url设置，请编写一个唯一的url，然后重试。");
			return new ModelAndView("ajaxResult", "result", result);
		}
		//修改文章后，可以立即返回视图给用户，此时分配一个线程去更新内存中tags数据
		new Thread(() -> {
			blogCommon.setTags(this.tagService.findAll());
		}).start();
		
		return new ModelAndView("ajaxResult", "result", result);
	}
	
	@RequestMapping(value="/admin/{articleId}/recovery",method=RequestMethod.POST)
	public ModelAndView recovery(@PathVariable Integer articleId){
		//恢复完再查询，确保事务顺序
		this.articleService.recovery(articleId);
		Pager<Article> pagerArticles = this.articleService.findPagerForAdmin(1);
		ModelAndView mav = new ModelAndView("/article/list", "pagerArticles", pagerArticles);
		mav.addObject("urlName", "/article/admin/list");
		mav.addObject("pageTitle", "文章列表");
		mav.addObject("duoshuoId", BlogConfig.DUOSHUO_ID);
		return mav;
	}
}
